<!--聊天对话-->
<template>
  <div class="padding-top-lg">
    <div v-for="(item, index) in chatHistory" :key="index">
      <!-- 用户输入 -->
      <div v-if="item.msgType === '1'" class="user-quiz margin-bottom">
        <div class="left-info wenzi margin-right-sm">
          <div class="bubble text-white">
            <div class="title">{{ item.content }}</div>
          </div>
        </div>
      </div>

      <!-- AI回复 -->
      <div v-else-if="item.msgType === '2'" class="ai-reply margin-bottom">
        <div class="flex align-center">
          <img width="35" src="../../../assets/image/aichat/aiRobot.png">
          <span class="padding-left-sm text-3D3D3D text-bold text-lg">能力推荐专家</span>
        </div>

        <!-- 新增：领域能力展示 -->
        <div v-if="item.domainInfo" class="domain-card bg-white margin-top-sm padding">
          <h2 class="text-xl text-bold text-3667B9 margin-bottom">{{ item.domainInfo.title }}</h2>
          <div class="domain-desc text-sm text-808080 margin-bottom">{{ item.domainInfo.desc }}</div>

          <!-- 可伸缩的能力列表 -->
          <div class="domain-abilities">
            <div class="abilities-header flex justify-between align-center" @click="toggleAbilities">
              <span class="text-bold">能力列表</span>
              <i :class="showAllAbilities ? 'el-icon-arrow-up' : 'el-icon-arrow-down'" class="el-icon"></i>
            </div>
            <div :class="{ 'expanded': showAllAbilities }" class="abilities-list">
              <div v-for="(ability, index) in item.domainInfo.abilities" v-show="showAllAbilities || index < 5"
                :key="index" class="ability-item padding-xs" @click="handleAbilityClick(ability)">
                {{ ability }}
              </div>
            </div>
            <div v-if="item.domainInfo.abilities.length > 5" class="show-more text-center text-primary cursor-pointer"
              @click="toggleAbilities">
              {{ showAllAbilities ? '收起' : '查看更多' }}
            </div>
          </div>
        </div>

        <!-- 能力卡片或普通文本回复 -->
        <div v-else-if="item.abilityInfoList && item.abilityInfoList.length > 0" class="card-swiper"
          @touchend="handleTouchEnd($event, item)" @touchmove="handleTouchMove($event, item)"
          @touchstart="handleTouchStart($event, item)">
          <!-- 卡片容器 -->
          <div :data-item-id="item.id" :style="{ transform: `translateX(${getTranslateX(item.id)}px)` }"
            class="cards-container">
            <div v-for="(ability, idx) in item.abilityInfoList" :key="idx" class="replay-card1 bg-white margin-top-sm">
              <div class="relative broadcast-box">
                <div class="absolute padding-top-xs padding-bottom-xs padding-right padding-left bg-blue">
                  <span class='cu-tag'>{{ ability.parentCapability }}</span>
                </div>
                <h1 class="text-3667B9 text-xl text-bold padding-bottom">{{ ability.name }}</h1>
                <div class="padding-bottom-xs">
                  <el-tag v-for="(tag, tagIdx) in ability.tags" :key="tagIdx" :class="{ 'margin-left-xs': tagIdx > 0 }"
                    class="tag-box">
                    {{ tag }}
                  </el-tag>
                </div>
                <div>
                  <div>
                    <div class="broadcast-title text-535353 text-bold">能力简介</div>
                    <div class="text-sm text-808080">{{ ability.description }}</div>
                  </div>
                  <div>
                    <div class="broadcast-title text-535353 text-bold">业务场景</div>
                    <div class="text-sm text-808080">{{ ability.scenarios }}</div>
                  </div>
                  <!-- 费用信息 -->
                  <div class="flex padding-top-sm price-container">
                    <div class="basis-sm price-box">
                      <div class="text-535353 text-bold padding-bottom-xs">首次接入费用</div>
                      <div :title="ability.firstCost ? `￥${ability.firstCost}` : '免费'"
                        class="text-lg text-FC7F04 price-text two-line">
                        {{ ability.firstCost ? `￥${ability.firstCost}` : '免费' }}
                      </div>
                    </div>
                    <div class="basis-sm price-box">
                      <div class="text-535353 text-bold padding-bottom-xs">年度服务费用</div>
                      <div :title="ability.yearCost" class="text-lg text-FC7F04 price-text two-line">
                        {{ ability.yearCost }}
                      </div>
                    </div>
                  </div>
                </div>
              </div>
              <!-- 按钮 -->
              <div class="broadcast-btn relative">
                <el-button class="btn" color="#1D6CFF" size="large"><a
                    href="https://d.xiumi.us/stage/v5/5eiOu/523525913#/" style="color: #fff; text-decoration: none; "
                    target="_blank">查看宣传页</a>
                </el-button>
              </div>
            </div>
          </div>

          <!-- 分页指示器 -->
          <div v-if="item.abilityInfoList.length > 1" class="card-indicators">
            <span v-for="(_, idx) in item.abilityInfoList" :key="idx"
              :class="{ active: getCardIndex(item.id) === idx }">
            </span>
          </div>
        </div>
        <div v-else class="content-text margin-top-sm bg-white" v-html="printedText"></div>
      </div>
    </div>

    <!-- 思考中提示 -->
    <div v-if="props.showLoading" class="ai-reply margin-bottom">
      <div class="flex align-center">
        <img src="../../../assets/image/aichat/aiRobot.png" width="35">
        <span class="padding-left-sm text-3D3D3D text-bold text-lg">能力推荐专家</span>
      </div>
      <div class="right-info">
        <div class="tip-box margin-top-sm bg-white">
          <div class="show-chat">
            <img height="20" src="../../../assets/image/common/load.gif" width="20" />
            <span v-for="(text, index) in props.showChatTipTxt" :key="index"
              :style="{ animationDelay: `${index * 0.1}s` }" class="show-chat-tip">
              {{ text }}
            </span>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { reactive, ref } from 'vue';
import { removeLastHash } from "@/utils/index.js";

const props = defineProps({
  // 对话历史记录
  chatHistory: {
    type: Array,
    default: () => []
  },
  // 文字提示
  showChatTipTxt: {
    type: String,
    default: '正在思考中...'
  },
  showLoading: {
    type: Boolean,
    default: false
  }
});
const emit = defineEmits(['askQuestion']);
const printedText = ref(''); // 需要打印出来的字符

const printStreamText = async (textToPrint, printFlag) => {
  console.info(textToPrint)
  if (printFlag === 'begin') { //开始打字

  } else if (printFlag == 'end') {

    printedText.value = await removeLastHash(printedText.value)


    printedText.value = ""
  }
  printedText.value += textToPrint
  console.info(printedText.value, 'printedText.value')
  emit('resetScroll')

}

const printText = (textToPrint) => {
  // 添加防护检查
  if (!textToPrint) {
    console.warn('No text to print');
    return;
  }

  printedText.value = '';
  const printInterval = setInterval(() => {
    if (printedText.value.length < textToPrint.length) {
      printedText.value += textToPrint[printedText.value.length];
      emit('resetScroll');
    } else {
      clearInterval(printInterval);
      emit('resetSubmit');
    }
  }, 10);
}

// 触摸相关状态
const touchState = reactive({
  startX: 0,
  currentX: 0,
  currentItemId: null,
  cardWidth: 0,
  isScrolling: false
});

// 存储每个对话的卡片索引和位移
const cardIndexMap = reactive(new Map());
const translateXMap = reactive(new Map());
const handleAbilityClick = (ability) => {
	// 使用预设的问题，如果没有则构造一个通用问题
	const question = ability.question || `请详细介绍${ability}的功能和使用场景`;
	emit('askQuestion', question);
}
// 获取当前卡片索引
const getCardIndex = (itemId) => {
  return cardIndexMap.get(itemId) || 0;
};

// 获取当前位移
const getTranslateX = (itemId) => {
  return translateXMap.get(itemId) || 0;
};

// 触摸开始
const handleTouchStart = (e, item) => {
  const touch = e.touches[0];
  touchState.startX = touch.clientX;
  touchState.currentX = touch.clientX;
  touchState.currentItemId = item.id;
  touchState.cardWidth = e.currentTarget.offsetWidth;
  touchState.isScrolling = false;

  // 初始化位移值（如果不存在）
  if (!translateXMap.has(item.id)) {
    translateXMap.set(item.id, 0);
  }
};

// 触摸移动
const handleTouchMove = (e, item) => {
  if (!touchState.currentItemId) return;

  const touch = e.touches[0];
  touchState.currentX = touch.clientX;
  const deltaX = touchState.currentX - touchState.startX;

  // 判断是否是水平滑动
  if (!touchState.isScrolling && Math.abs(deltaX) > 10) {
    touchState.isScrolling = true;
  }

  if (touchState.isScrolling) {
    // 阻止页面滚动
    e.preventDefault();

    const currentIndex = getCardIndex(item.id);
    const maxIndex = item.abilityInfoList.length - 1;
    const baseTranslate = -currentIndex * touchState.cardWidth;
    let newTranslate = baseTranslate + deltaX;

    // 限制滑动范围（添加弹性效果）
    if (newTranslate > 0) {
      newTranslate = deltaX / 3; // 减少过度滑动的距离
    } else if (newTranslate < -maxIndex * touchState.cardWidth) {
      const overScroll = newTranslate + maxIndex * touchState.cardWidth;
      newTranslate = -maxIndex * touchState.cardWidth + overScroll / 3;
    }

    // 更新位移
    translateXMap.set(item.id, newTranslate);
  }
};

// 触摸结束
const handleTouchEnd = (e, item) => {
  if (!touchState.currentItemId || !touchState.isScrolling) return;

  const deltaX = touchState.currentX - touchState.startX;
  const currentIndex = getCardIndex(item.id);
  const maxIndex = item.abilityInfoList.length - 1;

  // 计算新的索引
  let newIndex = currentIndex;
  if (Math.abs(deltaX) > touchState.cardWidth * 0.3) {
    newIndex = deltaX > 0 ? Math.max(0, currentIndex - 1) : Math.min(maxIndex, currentIndex + 1);
  }

  // 更新索引和位移
  cardIndexMap.set(item.id, newIndex);
  const finalTranslate = -newIndex * touchState.cardWidth;
  translateXMap.set(item.id, finalTranslate);

  // 重置状态
  touchState.currentItemId = null;
  touchState.isScrolling = false;
};

// 新增：控制能力列表展开/收起
const showAllAbilities = ref(false);

const toggleAbilities = () => {
  showAllAbilities.value = !showAllAbilities.value;
};

defineExpose({
  printStreamText,
  printText
})
</script>

<style scoped>
.ability-item {
  .left-box {
    width: 36px;
  }

  .right-box {
    width: calc(100% - 36px);
  }
}


.user-quiz {
  width: 100%;
  overflow: hidden;

  .wenzi {
    max-width: 70%;
    text-align: left;
    display: block;
    float: right;

    .bubble {
      padding: 10px 12px;
      display: inline-block;
      min-width: 16px;
      max-width: 100%;
      background: #768EDF url("../../../assets/image/aichat/sun.png") no-repeat left -120px top -50px;
      border-radius: 8px 0 8px 8px;
      word-break: break-all;
      letter-spacing: 1px;
      float: right;
    }

  }
}

.ai-reply {
  width: 100%;

  .replay-card1,
  .replay-card2 {
    box-shadow: none;
    border: none;
    border-radius: 8px;
  }

  /*卡片1*/

  .replay-card1 {
    padding: 12px 12px 0 12px;

    .absolute {
      right: -12px;
      top: -12px;
    }

    .bg-blue {
      background: #3E7FE3;
      border-radius: 2px 7px 2px 18px;
    }


    .broadcast-btn {
      bottom: 20px;
      width: 100%;

      .btn {
        display: flex;
        margin: 0 auto;
        border-radius: 8px;
        width: 80%;
      }
    }

    .broadcast-box {
      min-height: 400px;
      padding: 2px 15px;
      background: url('../../../assets/image/aiChatApp/card-1.png') no-repeat;
      background-size: 100% 100%;

      .broadcast-title {
        padding: 8px 0;
      }
    }
  }

  /*卡片2*/

  .replay-card2 {
    padding: 17px 0 42px 0;

    .safe-box {
      .ability-list {
        z-index: 9;
      }

      .open-more {
        bottom: 10px;
        left: calc(50% - 35px);
        color: #1D6CFF;
      }

      .iconfont {
        margin-top: 2px;
        font-size: 10px;
      }
    }

    .safe-bg {
      top: 10px;
      right: 0;
      float: right;
      width: 144px;
      height: 220px;

      background: url('../../../assets/image/aiChatApp/card-2.png') no-repeat left;
      background-size: 100% 100%;
    }
  }

  .right-info {
    width: 100%;

    .tip-box,
    .content-text {
      color: #414141;
      padding: 12px;
      border-radius: 0px 8px 8px 8px;
      box-shadow: 0px 0px 0px 0px rgba(171, 197, 232, 0.4);

      letter-spacing: 1px;
      text-align: justify;


    }

    .tip-box {
      width: 140px;

      .show-chat {
        display: flex;
        align-items: center;

        .show-chat-tip {
          font-size: 14px;
          color: #666060;
          animation: bounce 1.5s ease-in-out infinite;
        }
      }
    }

    .content-text {
      width: 100%;
    }
  }

}

.tag-box {
  background: rgba(62, 127, 227, 0.1);
  color: #3E7FE3;
}

.text-535353 {
  color: #535353;
}

.price-container {
  gap: 12px;
  /* 添加间距 */
}

.price-box {
  flex: 1;
  min-width: 0;
  /* 允许子元素收缩 */
}

.price-text {
  font-size: 14px;
  line-height: 1.3;
}

.two-line {
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: normal;
  word-break: break-all;
  min-height: 36px;
  /* 确保两行高度 */
}

.card-swiper {
  position: relative;
  width: 100%;
  overflow: hidden;
  touch-action: pan-y pinch-zoom;
}

.cards-container {
  display: flex;
  width: 100%;
  will-change: transform;
  transition: transform 0.3s ease;
}

.replay-card1 {
  flex: 0 0 100%;
  width: 100%;
  user-select: none;
  -webkit-user-drag: none;
}

.card-indicators {
  display: flex;
  justify-content: center;
  gap: 8px;
  margin-top: 12px;
}

.card-indicators span {
  width: 8px;
  height: 8px;
  border-radius: 50%;
  background: #ddd;
  cursor: pointer;
  transition: background-color 0.3s;
}

.card-indicators span.active {
  background: #1D6CFF;
}

@keyframes bounce {

  0%,
  100% {
    transform: translateY(0);
  }

  50% {
    transform: translateY(-5px);
  }
}

/* 新增领域卡片相关样式 */
.domain-card {
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.domain-desc {
  line-height: 1.5;
}

.domain-abilities {
  border-top: 1px solid #eee;
  margin-top: 12px;
  padding-top: 12px;
}

.abilities-header {
  cursor: pointer;
  padding: 8px 0;
}

.abilities-list {
  max-height: 120px;
  overflow: hidden;
  transition: max-height 0.3s ease-in-out;
}

.abilities-list.expanded {
  max-height: none;
}

.ability-item {
  border-radius: 4px;
  margin: 4px 0;
}

.ability-item:hover {
  background-color: #f5f7fa;
}

.show-more {
  color: #1D6CFF;
  padding: 8px 0;
  margin-top: 8px;
  border-top: 1px solid #eee;
}
</style>
